<?php

namespace app\index\service;

use app\common\ConfigBase;
use app\common\model\ToolModel;
use app\index\model\NewskuModel;
use app\index\model\UserModel;
use think\Cache;
use think\Db;

class NewskuService
{
    //获取新品sku列表
    static public function getNewSkuList($param)
    {
        $titles = [
            'sku' => 'SKU',
            'spu' => 'SPU',
            'name' => 'SKU名称',
            'creation_time' => '录入时间',
            'modification_time' => '最后操作时间',
            'modification_operator' => '最后操作人',
            'status_str' => 'sku状态',
            'sales_status_str' => '销售状态',
            'remarks' => '备注',
            'develop_code' => '开发编码',
            'developer_name' => '开发人员',
            'cate_name_path' => '分类信息',
            'category_id' => '分类ID',
            'eancode' => 'EAN码',
            'develop_time' => '开发日期',
            'serviceline_str' => '业务线',
            'asweight' => '自带包装重量',
            'standard' => '制式',
            'develop_link' => '开发链接',
            'old_erp_id' => '老erp ID',
            'reference_price' => '参考价',
            'qc_standard' => '质检标准',
        ];
        return NewskuModel::getNewSkuList($param, $titles, "\app\index\service\NewskuService::getNewSkuListHandle");
    }

    //列表处理
    static public function getNewSkuListHandle($data)
    {
        $status = ConfigBase::$skuStatus;
        $serviceLine = ConfigBase::$serviceLine;
        $saleStatus = ConfigBase::$skuSaleStatus;
        $data1 = ToolModel::select('sku_attribute', ['sku' => ['in', array_column($data, 'sku')]],
            'develop_code,develop_link,develop_time,eancode,developer,old_erp_id,
            qc_standard,remarks,standard,uptime,
            baleweight,balelength,balewide,balehight,
            length,wide,hight,quantity_unit,quantity,bulk,bulk_unit,
            ashight,aswide,aslength,asweight
            ',
            '', 'sku');
        $cate = ToolModel::select('common_categories', ['id' => ['in', array_column($data, 'category_id')]], 'category', '', 'id');
        $catePath = ToolModel::select('common_categories_path', ['cate_id' => ['in', array_column($data, 'category_id')]], 'cate_name_path,cate_id_path', '', 'cate_id');

        $develop = UserModel::getUserById(array_column($data1, 'developer'));

        $u=session('user');
        $role=json_decode($u['auth'],true);
        if(empty($role)){
            $role=[];
        }
        if(in_array(64,$role)){
            $updatePrice=1;
        }else{
            $updatePrice=0;
        }
        foreach ($data as &$v) {
            $v['status_str'] = $status[$v['status']];
            $v['sales_status_str'] = $saleStatus[$v['sales_status']] ?? '';
            if (!empty($data1[$v['sku']])) {
                $v = array_merge($data1[$v['sku']], $v);
                $v['developer_name'] = $develop[$v['developer']] ?? '';
            }
            $v['category_str'] = $cate[$v['category_id']] ?? '';
            $v['cate_name_path'] = !empty($catePath[$v['category_id']]) ?$catePath[$v['category_id']]['cate_name_path']: '';
            $v['cate_id_path'] = !empty($catePath[$v['category_id']])  ?$catePath[$v['category_id']]['cate_id_path']: '';
            $v['serviceline_str'] = $serviceLine[$v['serviceline']]??'';
            $v['updatePrice']=$updatePrice;
            if(empty($v['develop_time'])||$v['develop_time']=='0000-00-00'){
                $v['develop_time']='';
            }
            $v['length_temp']=$v['length'];
            unset($v['length']);
        }
        return $data;
    }

    static public function getCate($param)
    {
        //cate_id pid children cate_name cate_name_cn
        $cache = Cache::get('skuCate');
        if ($cache && empty($param['cache'])) {
            return $cache;
        }
        $cate = Db::table('common_categories')
            ->field("category as cate_name,id as cate_id,pare_id as pid")
            ->select();
        $res = SkuAttrService::toTree($cate);
        Cache::set('skuCate', $res, 0);
        return $res;
    }

    static public function editSku($param)
    {
        $data1 = $data2 = [];
        $data1['spu'] = $param['spu'];
        $data1['name'] = $param['name'];
        $data1['category_id'] = $param['category_id'];
        $data1['status'] = $param['status'];
        $data1['serviceline'] = $param['serviceline'];
        $data1['modification_time'] = TIME;
        $data1['modification_operator'] = CN_NAME;
        ToolModel::updateData(['sku' => $param['sku']], $data1, 'skus');
        $data2['develop_code'] = $param['develop_code'];
        $data2['develop_time'] = $param['develop_time'];
        $data2['develop_link'] = $param['develop_link'];
        $data2['asweight'] = $param['asweight'];
        empty($data2['uptime']) && $data2['uptime'] = null;
        empty($data2['develop_time']) && $data2['develop_time'] = null;

        if ($data2['asweight'] > 0) {
            if (bccomp($data2['asweight'], 100, 5) == 1) {
                $data2['baleweight'] = $data2['asweight'] + ($data2['asweight'] * 0.1);
            } else {
                if ($data2['asweight'] >= 50) {
                    $data2['baleweight'] = $data2['asweight'] + 10;
                } else {
                    $data2['baleweight'] = $data2['asweight'] + 5;
                }
            }
        }
        $data2['eancode'] = $param['eancode'];
        $data2['standard'] = $param['standard'];
        $data2['developer'] = $param['developer'];
        $data2['old_erp_id'] = $param['old_erp_id'];
        $data2['qc_standard'] = $param['qc_standard'];
        $data2['modification_time'] =date('Y-m-d H:i:s');
        $data2['modification_operator'] = CN_NAME;
        ToolModel::updateData(['sku' => $param['sku']], $data2, 'sku_attribute');

        //改交接表
        ToolModel::updateData(['sku' => $param['sku'], 'status' => ['<>', 4]], ['spu' => $param['spu'], 'developer' => $param['developer']], 'sku_handover');
    }

    static public function editSkuSaleStatus($param)
    {
        if ($param['sales_status'] == 3) {
            return returnArr(2, '不能改为缺货状态!');
        }
        ToolModel::updateData(['sku' => $param['sku']], ['modification_time'=>date('Y-m-d H:i:s'),'sales_status' => $param['sales_status'],'modification_operator'=>CN_NAME], 'skus');
        ToolModel::updateData(['sku' => $param['sku']], ['remarks' => $param['remarks'],'modification_operator'=>CN_NAME], 'sku_attribute');
        return returnArr();
    }
    static public function editSkuPrice($param)
    {
        if (empty($param['reference_price'])||$param['reference_price']<0) {
            return returnArr(2, '参考价不能小于等于0');
        }
        ToolModel::updateData(['sku' => $param['sku']], ['modification_time'=>date('Y-m-d H:i:s'),'reference_price' => $param['reference_price'],'modification_operator'=>CN_NAME], 'skus');
        ToolModel::dbInsertOrUpdate('updateprice_remove_skus',[
            array(
                'sku' => $param['sku'],'remark'=>'修改人'.CN_NAME.'修改价格'. $param['reference_price']
            )
        ],[],'yf');
        return returnArr();
    }
    //上传新品sku处理
    static public function uploadAdd($data, $param)
    {
        $error = [];
        $serviceLine = array_flip(ConfigBase::$serviceLine);
        $user = UserModel::getUserByNike(array_column($data, '8'));
        $cate = NewskuModel::getCateById(array_column($data, '13'));
        $skus = NewskuModel::getSkuBySku(array_column($data, '3'));
        $standard = array_flip(ConfigBase::$standard);
        $dataMain = [];
        $dataMinor = [];
        $name = $param['cn_name'];
        $skuArr=[];
        foreach ($data as $v) {
            $sku = $v[3];
            $data1 = [];
            $data2 = [];
            $data1['sku'] = $sku;
            $data1['spu'] = $v[1];
            $data1['name'] = $v[4];
            $data2['develop_code'] = $v[2];
            $data2['developer'] = $user[$v[8]] ?? '';
            $data1['category_id'] = $v[13];
            $data2['eancode'] = $v[10];
            $data2['develop_time'] = $v[0];
            $data1['serviceline'] = $serviceLine[$v[11]] ?? '';
            $data2['asweight'] = round($v[5]);
            $data2['standard'] = $v[12];
            $data2['develop_link'] = $v[7];
            $data2['old_erp_id'] = $v[9];
            $data1['reference_price'] = $v[6];
            $data2['qc_standard'] = $v[14];
            if (!empty($skus[$sku])) {
                $error[] = "SKU: {$sku} 已存在!  ";
                continue;
            }
            if (!checkSku($sku)) {
                $error[] = "SKU: {$sku} 格式不正确!  ";
            }
            if(in_array($sku,$skuArr)){
                $error[] = "SKU: {$sku} 在上传文件里有重复!  ";

            }
            $skuArr[]=$sku;
            if (!preg_match('/^[1-9][0-9]*$/', $data1['spu'])) {
                $error[] = "SKU: {$sku}  spu: {$data1['spu']} 格式必须为数字!  ";
            }
            if (empty($data1['serviceline'])) {
                $error[] = "SKU: {$sku}  找不到对应的业务线:{$data1['serviceline']}!";

            }
            if (empty($data2['developer'])) {
                $error[] = "SKU: {$sku}  找不到对应的开发员:{$data2['developer']}!";

            }
            if (empty($cate[$data1['category_id']])) {
                $error[] = "SKU: {$sku}  找不到对应的跟分类:{$data1['category_id']}!";


            }
            if (empty($standard[$data2['standard']])) {
                $error[] = "SKU: {$sku} 制式不正确!  ";
            }
            if(strtotime($data2['develop_time'])<1104545575){
                $error[] = "SKU: {$sku} 开发日期 {$data2['develop_time']} 格式不正确,正确格式为2019/10/1 !  ";
            }

            if (!preg_match('/^[1-9][0-9]*$/', $data2['asweight'])) {
                $error[] = "SKU: {$sku} 自带包装重量: {$data2['asweight']} 格式必须为全整数!  ";

            }
            if(!empty($data2['develop_link'])){
                if($data2['develop_link']=='送样'){

                }else{
                    if(!preg_match("/^http(s)?:\\/\\/.+/",$data2['develop_link'])){
                        $error[] = "SKU: {$sku}  {$data2['develop_link']} 开发链接正确格式应为 http://baidu.com !";
                    }
                }
            }









            foreach ($data1 as $v1) {
                if (empty($v1)) {
                    $error[] = "除了EAN码其他字段都要必填!";
                }
            }
            foreach ($data2 as $k2 => $v2) {
                if ($k2 != 'eancode' && empty($v2)) {
                    $error[] = "除了EAN码其他字段都要必填!";
                }
            }

            if ($data2['asweight'] > 0) {
                if (bccomp($data2['asweight'], 100, 5) == 1) {
                    $data2['baleweight'] = $data2['asweight'] + ($data2['asweight'] * 0.1);
                } else {
                    if($data2['asweight']>=50){
                        $data2['baleweight'] = $data2['asweight'] + 10;
                    }else{
                        $data2['baleweight'] = $data2['asweight'] + 5;
                    }
                }
            }

            $data1['creation_time'] = TIME;
            $data1['modification_operator'] = $name;
            $data1['operator'] = $name;
            $data2['modification_operator'] = $name;
            $data2['sku'] = $sku;
            $dataMain[] = $data1;
            $dataMinor[] = $data2;
        }
        //错误信息输出
        if (!empty($error)) {
            return returnArr(2, '', $error);
        }
        unset($data);
        ToolModel::insertData($dataMain, 'skus');
        unset($dataMain);
        ToolModel::insertData($dataMinor, 'sku_attribute');
        unset($dataMinor);
        //成功
        return returnArr();
    }

    //上传更新sku信息
    static public function uploadUpdate($data, $param)
    {
        $error = [];
        $serviceLine = array_flip(ConfigBase::$serviceLine);
        $user = UserModel::getUserByNike1(array_column($data, '4'));
        $cate = NewskuModel::getCateById(array_column($data, '5'));
        $skus = NewskuModel::getSkuBySku(array_column($data, '0'));
        $standard = array_flip(ConfigBase::$standard);
        $handover = ToolModel::select('sku_handover', ['sku'=>['IN',array_column($data, '0')]], 'status','','sku');
        $dataMain = [];
        $dataMinor = [];
        $dataHandover = [];
        $name = $param['cn_name'];
        $skuArr=[];
        foreach ($data as $v) {
            $sku = $v[0];
            $skuArr[]=$sku;
            $data1 = [];
            $data2 = [];
            $data3 = [];
            $data1['sku'] = $sku;
            !empty($v[1]) && $data1['spu'] = $v[1];
            !empty($v[2]) && $data1['name'] = $v[2];
            !empty($v[3]) && $data2['develop_code'] = $v[3];
            !empty($v[4]) && $data2['developer'] = $user[$v[4]] ?? '';
            !empty($v[5]) && $data1['category_id'] = $v[5];
            !empty($v[6]) && $data2['eancode'] = $v[6];
            !empty($v[7]) && $data2['develop_time'] = $v[7];
            !empty($v[8]) && $data1['serviceline'] = $serviceLine[$v[8]] ?? '';
            !empty($v[9]) && $data2['standard'] = $v[9];
            !empty($v[10]) && $data2['develop_link'] = $v[10];
            !empty($v[11]) && $data2['old_erp_id'] = $v[11];
            !empty($v[12]) && $data2['qc_standard'] = $v[12];
            !empty($v[13]) && $data2['asweight'] = $v[13];
            !empty($v[14]) && $data2['baleweight'] = $v[14];
            if(!empty($v[15])){
                $assize = explode('*', $v[15]);
                $data2['aslength'] = $assize[0]??0;
                $data2['aswide'] = $assize[1]??0;
                $data2['ashight'] = $assize[2]??0;
                if(isset($handover[$sku]) && $handover[$sku] < 5){
                    $data3['aslength'] = $assize[0]??0;
                    $data3['aswide'] = $assize[1]??0;
                    $data3['ashight'] = $assize[2]??0;
                }
            }
            if(!empty($v[16])){
                $balesize = explode('*', $v[16]);
                $data2['balelength'] = $balesize[0]??0;
                $data2['balewide'] = $balesize[1]??0;
                $data2['balehight'] = $balesize[2]??0;
            }
            if(!empty($v[17])){
                $data2['bulk'] = $v[17];
                if(isset($handover[$sku]) && $handover[$sku] < 5)
                    $data3['bulk'] = $v[17];
            }
            if(!empty($v[18])){
                $data2['bulk_unit'] = $v[18];
                if(isset($handover[$sku]) && $handover[$sku] < 5)
                    $data3['bulk_unit'] = $v[18];
            }
            if (empty($skus[$sku])) {
                $error[] = "SKU: {$sku} 不存在!  ";
            }
            if (!checkSku($sku)) {
                $error[] = "SKU: {$sku} 格式不正确!  ";
            }
            if(!empty( $data2['develop_time'])&&strtotime($data2['develop_time'])<1104545575){
                $error[] = "SKU: {$sku} 开发日期 {$data2['develop_time']} 格式不正确,正确格式为2019/10/1 !  ";
            }
            if (!empty($data1['spu']) && !preg_match('/^[1-9][0-9]*$/', $data1['spu'])) {
                $error[] = "spu: {$data1['spu']} 格式必须为数字!  ";
            }
            if (!empty($v[8]) && empty($data1['serviceline'])) {
                $error[] = "找不到对应的业务线:{$data1['serviceline']}!";
            }
            if($v[4]!='空'){
                if (!empty($v[4]) && empty($data2['developer'])) {
                    $error[] = "找不到对应的开发员:{$data2['developer']}!";
                }
            }else{
                $data2['developer']=null;
            }
            if (!empty($data1['category_id']) && empty($cate[$data1['category_id']])) {
                $error[] = "找不到对应的跟分类:{$data1['category_id']}!";
            }
            if (!empty($data2['standard']) && empty($standard[$data2['standard']])) {
                $error[] = "SKU: {$sku} 制式不正确!  ";
            }
            if (!empty($data1)) {
                $data1['modification_operator'] = $name;
                $data1['sku'] = $sku;
                $dataMain[] = $data1;
            }
            if (!empty($data2)) {
                $data2['modification_operator'] = $name;
                $data2['sku'] = $sku;
                $dataMinor[] = $data2;
            }

            if (!empty($data3)) {
                $data3['modification_operator'] = $name;
                $data3['sku'] = $sku;
                $dataHandover[] = $data3;
            }
        }
        unset($data);
        //错误信息输出
        if (!empty($error)) {
            return returnArr(2, '', $error);
        }
        foreach ($dataMain as $v3) {
            ToolModel::updateData(['sku' => $v3['sku']], $v3, 'skus');
        }
        unset($dataMain);
        foreach ($dataMinor as $v4) {
            ToolModel::updateData(['sku' => $v4['sku']], $v4, 'sku_attribute');
        }
        unset($dataMain);
        foreach ($dataHandover as $v5) {
            ToolModel::updateData(['sku' => $v5['sku']], $v5, 'sku_handover');
        }
        unset($dataHandover);
        ToolModel::updateData(['sku'=>['in',$skuArr]],['modification_time'=>date('Y-m-d H:i:s')],'skus');
        //成功
        return returnArr();
    }

    static public function uploadUpdateSaleStatus($dataAll, $param){
        $dataChunk=array_chunk($dataAll,20000);
        $skuSaleStatus=array_keys(ConfigBase::$skuSaleStatus);
        $error = [];
        foreach ($dataChunk as $data){
            $skuArr=array_column($data, '0');
            $skus=Db::table('skus')->where(['sku'=>['in',$skuArr]])
                ->column('sku,sales_status_old,sales_status','sku');
            $data1=[];
            $data2=[];
            $data11=[];
            $data22=[];
            foreach ($data as $v) {
                $temp=[];
                $temp2=[];
                $temp['sku'] = $v[0];
                $temp['sales_status'] = $v[1];
                !empty($v[3])&&$temp2['remarks'] = $v[3];
                $temp2['sku'] =$v[0];
                if (empty($skus[$temp['sku']])) {
                    //$error[] = "SKU: {$temp['sku']} 不存在!  ";
                    continue;
                }
                if(!empty($temp['sales_status'])){
                    if(!in_array($temp['sales_status'],$skuSaleStatus)){
                        $error[] = "SKU: {$temp['sku']} 销售状态只能是数字!  ";
                        continue;
                    }

                    $temp['modification_operator']= $param['cn_name'];
                    if($skus[$temp['sku']]['sales_status']!=$temp['sales_status']){
                        $temp['sales_status_old'] =$temp['sales_status'];
                        $data11[]=$temp;
                    }else{
                        $data1[]=$temp;
                    }
                }
                if(!empty($v[2])){
                    if(strtotime($v[2])<1104545575){
                        $error[] = "SKU: {$temp['sku']} 上架日期 {$v[2]} 格式不正确,正确格式为2019/10/1 !  ";
                        continue;
                    }
                    $temp2['uptime'] = $v[2];
                    $temp2['modification_operator']= $param['cn_name'];
                    $data22[]=$temp2;
                }elseif(!empty($temp2['remarks'])){
                    $temp2['modification_operator']= $param['cn_name'];
                    $data2[]=$temp2;
                }
            }
            //错误信息输出
            if (!empty($error)) {
                return returnArr(2, '', $error);
            }
            !empty($data1)&&ToolModel::dbInsertOrUpdate('skus',$data1);
            !empty($data2)&&ToolModel::dbInsertOrUpdate('sku_attribute',$data2);
            !empty($data11)&&ToolModel::dbInsertOrUpdate('skus',$data11);
            !empty($data22)&&ToolModel::dbInsertOrUpdate('sku_attribute',$data22);
            //ToolModel::updateData(['sku'=>['in',$skuArr]],['modification_time'=>date('Y-m-d H:i:s')],'skus');
        }
        return returnArr();
    }
    static public function uploadUpdateStatus($data, $param){
        $skus=Db::table('skus')->where(['sku'=>['in',array_column($data, '0')]])
            ->column('sku,sales_status_old,sales_status','sku');
        $data1=[];
        $status=[
            '启用'=>1,
            '禁用'=>0
        ];
        $error = [];
        foreach ($data as $v) {
            $temp=[];
            $temp['sku'] = $v[0];
            $temp['status'] = $status[$v[1]]??'';
            if (empty($skus[$temp['sku']])) {
                $error[] = "SKU: {$temp['sku']} 不存在!  ";
                continue;
            }
            if(!in_array($temp['status'],$status)){
                $error[] = "SKU: {$temp['sku']} 状态只能是启用或禁用!  ";
                continue;
            }
            $temp['modification_operator']=$param['cn_name'];
            $temp['modification_time']=date('Y-m-d H:i:s');
            $data1[]=$temp;
        }
        //错误信息输出
        if (!empty($error)) {
            return returnArr(2, '', $error);
        }
        !empty($data1)&&ToolModel::dbInsertOrUpdate('skus',$data1);
        return returnArr();
    }
    static public function uploadUpdatePrice($data, $param){
        $skus=Db::table('skus')->where(['sku'=>['in',array_column($data, '0')]])
            ->column('sku,reference_price,id','sku');
        $data1=[];
        $data2=[];
        $error = [];
        foreach ($data as $v) {
            $temp=[];
            $temp['sku'] = $v[0];
            $temp['reference_price'] = $v[1];
            if (empty($skus[$temp['sku']])) {
                $error[] = "SKU: {$temp['sku']} 不存在!  ";
                continue;
            }
            if (empty($temp['reference_price']||$temp['reference_price']<0)) {
                $error[] = "SKU: {$temp['sku']} 参考价不能小于等于0!  ";
                continue;
            }
            $temp['modification_operator']=$param['cn_name'];
            $temp['modification_time']=date('Y-m-d H:i:s');
            $data1[]=$temp;
            $data2[]=[
                'sku'=> $temp['sku'],'remark'=>'修改人'.$param['cn_name'].'修改价格'. $temp['reference_price']
            ];
        }
        //错误信息输出
        if (!empty($error)) {
            return returnArr(2, '', $error);
        }
        !empty($data1)&&ToolModel::dbInsertOrUpdate('skus',$data1);
       /* !empty($data2)&&ToolModel::dbInsertOrUpdate('updateprice_remove_skus',$data2,[],'yf');*/
        return returnArr();
    }

}